//
//  LGTRWZOperateRecodeVC.swift
//  KJLGT
//
//  Created by jenkin on 2019/8/29.
//  Copyright © 2019年 jenkin. All rights reserved.
//

import UIKit

class LGTRWZOperateRecodeVC: LGTBaseVC, UITableViewDelegate, UITableViewDataSource, HJImageBrowserDelegate{
    func getTheThumbnailImage(_ indexRow: Int) -> UIImage {
        return UIImage.init()
    }
    
    //订单详情请求参数
    var orderModel:TaskOrderModel?
    var tableView:UITableView?
    //操作记录
    var data:Array<Dictionary<String, Any>> = []
    var imageClickBlock:ClickImageIndexBlock?
    //订单参数
    var taskDetailInfo:Dictionary<String, Any> = [:]
    //返回订单详情
    var updateOrderBlock:ClickInfoBlock?
    //操作订单成功处理
    var opetateSuccessBlock:ClickBlock?  //操作记录修改订单状态
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setBlock()
    }
    
    func setBlock(){
        self.imageClickBlock = {(data:Dictionary<String, Any>, index:Int, view:UIView) in
            let imageArray:Array<Dictionary<String, Any>> = data["image"] as? Array<Dictionary<String, Any>> ?? []
            var urlArray:Array<String> = []
            for image in imageArray{
                let url:String = image["url"] as? String ?? ""
                urlArray.append(url)
            }
            
            if urlArray.count == 0{
                return
            }
            
            let bview = HJImageBrowser()
            bview.delegate = self
            bview.bottomView = view.superview!
            bview.indexImage = index
            bview.defaultImage = getColorImageWithColor()
            bview.arrayImage = urlArray
            bview.show()
        }
        
        weak var weakSelf = self
        self.updateOrderBlock = {(index:Int, info:Dictionary<String, Any>) in
            weakSelf?.dataChange(json: info)
        }
    }
    
    override func setUI() {
        super.setUI()
        
        let status:Int = self.taskDetailInfo["status"] as? Int ?? 0
        let viewType:DetailType = self.taskDetailInfo["viewType"] as? DetailType ?? .RWZ_PreView_Type
        var bottomH:Double = 0
        //申诉待处理8   待审核4 //拒绝 通过
        if viewType == .RWZ_OrderView_Type  && (status == 4 || status == 8){
            bottomH = TabBarH()
        }

        self.setBavBarStyle(navBarHiden: false, title: "操作记录", back: true)
        if bottomH > 0{
            let giveupBtn:UIButton = LGTViewCreateUtil.share.createButtonTitleAndImage(imageName: "refuse", title: "拒绝", color:TextColor, font: Font_Normal_18, backColor: UIColor.white)
            self.view.addSubview(giveupBtn)
            giveupBtn.snp.makeConstraints { (make) in
                make.bottom.equalTo(0)
                make.left.equalTo(0)
                make.width.equalTo(KScreenW/3)
                make.height.equalTo(TabBarH())
            }
            giveupBtn.tag = LGTRWZDetailBtnType.RWZRefuseType.rawValue
            giveupBtn.addTarget(self, action: #selector(postAction), for: UIControl.Event.touchUpInside)

            let submitBtn:UIButton = LGTViewCreateUtil.share.createButtonTitleAndImage(imageName: "adopt", title: "通过", color:UIColor.white, font: Font_Normal_18, backColor: YellowColor)
            self.view.addSubview(submitBtn)
            submitBtn.snp.makeConstraints { (make) in
                make.bottom.right.equalTo(0)
                make.left.equalTo(giveupBtn.snp_rightMargin)
                make.height.equalTo(TabBarH())
            }
            submitBtn.tag = LGTRWZDetailBtnType.RWZPassType.rawValue
            submitBtn.addTarget(self, action: #selector(postAction), for: UIControl.Event.touchUpInside)
        }
        
        self.tableView = UITableView.init(frame: CGRect.init(x: 0.0, y: NavBarH(), width: Double(KScreenW), height: Double(KScreenH) - NavBarH() - bottomH), style: UITableView.Style.plain)
        self.view.addSubview(self.tableView!)
        self.tableView?.backgroundColor = ViewBackColor
        self.tableView?.separatorStyle = UITableViewCell.SeparatorStyle.none
        self.tableView?.delegate = self as UITableViewDelegate
        self.tableView?.dataSource = self as UITableViewDataSource
        self.tableView?.register(LGTRWZOpetateRecodeCell.classForCoder(), forCellReuseIdentifier: "cell")
        
        self.tableView?.estimatedRowHeight = 40
        self.tableView?.rowHeight = UITableView.automaticDimension
        self.tableView?.backgroundColor = ViewBackColor
        self.tableView?.reloadData()
    }
    
    
    @objc func postAction(sender:UIButton){
        
        let index:Int = sender.tag
        //拒绝
        if index == LGTRWZDetailBtnType.RWZRefuseType.rawValue{
            self.refuse()
        }
        //通过
        else{
            self.pass()
        }
    }
    
    //通过 8申诉通过 4审核通过
    func pass(){
        //申诉待处理8   待审核4
        weak var weakSelf = self
        self.showAlerView(title: "温馨提示", desc: "您确定要通过此任务单吗？", subText: "确认后佣金将转给该用户", sureBlock: {
            var status:Int = 5  // 审核通过状态
            if weakSelf?.orderModel?.status == 8{
                status = 9 //申诉通过状态
            }
            let param:Dictionary<String, Any> = ["id":weakSelf?.orderModel?.id ?? 0, "status":status]
            self.orderAction(url: RWZ_OrderStatus_Update_URL, param: param)
        }) {
            
        }
    }
    
    //拒绝
    func refuse(){
        let vc:LGTRefuseAlertVC = LGTRefuseAlertVC()
        vc.clickInfoBlock = updateOrderBlock
        vc.orderModel = self.orderModel
        vc.modalPresentationStyle = .overCurrentContext
        self.present(vc, animated: false, completion: nil)
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.data.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell:LGTRWZOpetateRecodeCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as!  LGTRWZOpetateRecodeCell
        
        var model:Dictionary<String, Any> = self.data[indexPath.row]
        if indexPath.row == 0{
            model["istop"] = true
        }else if indexPath.row == self.data.count - 1{
            model["isbottom"] = true
        }
        cell.model = model
        cell.imageClickBlock = self.imageClickBlock
        return cell
    }
    
    
    //网络请求
    func orderAction(url:String, param:Dictionary<String, Any>){
        weak var weakSelf = self
        LGTHttpUtil.httpUtil.requestData(url: url, param: param, showMessage: true, success: { (json) in
            weakSelf?.dataChange(json: json)
        }) { (json) in
        }
    }
    
    //数据更改
    func dataChange(json:Dictionary<String, Any>){
        var data:Dictionary<String, Any> = json["data"] as? Dictionary<String, Any> ?? [:]
        let paramsStr:String = data["params"] as? String ?? ""
        let paramsInfo:Dictionary<String, Any> = BaseUtil.baseUtil.getDictionaryFromJSONString(jsonString: paramsStr)
        let timeStepArray:Array<Dictionary<String, Any>> = paramsInfo["time_step"] as? Array<Dictionary<String, Any>> ?? []
        self.data = timeStepArray
        self.tableView?.frame = CGRect.init(x: 0.0, y: NavBarH(), width: Double(KScreenW), height: Double(KScreenH) - NavBarH())
        self.tableView?.reloadData()
        
        //订单状态修改成功
        if self.opetateSuccessBlock != nil{
            self.opetateSuccessBlock!()
        }
    }
}
